package Offer.q41_MovingAverage;

public class MovingAverage {
    /*
    用队列可以很简单的模拟一个窗口
    但是数组可能能够减少内存
     */
    int[] arr;
    int p, count;
    double sum;
    public MovingAverage(int size) {
        arr = new int[size];
        p = 0;
        count = 0;
        sum = 0;
    }

    public double next(int val) {
        if (count < arr.length) {
            arr[count] = val;
            ++count;
            sum += val;
            return sum / count;
        } else {
            sum -= arr[p % arr.length];
            arr[p % arr.length] = val;
            sum += val;
            ++p;
            return sum / arr.length;
        }
    }
}
